<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>糖尿病数据分析大屏</title>
  <!-- Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- Font Awesome（修改为CDN链接） -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <!-- ECharts -->
  <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>

  <!-- 自定义 Tailwind 配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            warning: '#FF9F43',
            danger: '#FF5252',
            dark: '#1E293B',
            'light-blue': '#E6F7FF',
            'card-bg': '#F5F7FA',
            'border-light': '#E5E9F2',
          },
          fontFamily: {
            inter: ['Inter', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <!-- 自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      }
      .card-hover {
        transition: all 0.3s ease;
      }
      .card-hover:hover {
        transform: translateY(-5px);
        box-shadow: 0 12px 20px rgba(22, 93, 255, 0.15);
      }
      .animate-float {
        animation: float 6s ease-in-out infinite;
      }
      @keyframes float {
        0% { transform: translateY(0px); }
        50% { transform: translateY(-10px); }
        100% { transform: translateY(0px); }
      }
    }
  </style>

  <style>
    body {
      background-color: #F5F7FA;
      color: #1E293B;
      font-family: 'Inter', sans-serif;
    }

    .bg-white.rounded-xl.p-5.mb-8.card-shadow {
        display: none !important; /* 强制隐藏元素 */
    }
    /* 加载动画 */
    .loader {
      border-top-color: #165DFF;
      animation: spinner 1s linear infinite;
    }
    @keyframes spinner {
      0% {
        transform: rotate(0deg);
      }
      100% {
        transform: rotate(360deg);
      }
    }

    /* 数字动画 */
    @keyframes countUp {
      from {
        opacity: 0;
        transform: translateY(10px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
    .count-animate {
      animation: countUp 0.8s ease forwards;
    }

    /* 日期时间数字动画 */
    @keyframes pulse {
      0%, 100% {
        opacity: 1;
      }
      50% {
        opacity: 0.7;
      }
    }
    .time-digit {
      transition: all 0.3s ease;
    }
    .time-separator {
      animation: pulse 2s infinite;
    }
  </style>
</head>
<body class="min-h-screen">
  <!-- 导航栏 -->
  <nav class="bg-primary text-white p-4 h-16 shadow-lg">
    <div class="container mx-auto flex justify-between items-center">
      <h1 class="text-2xl font-bold flex items-center">
        <i class="fa-solid fa-heartbeat mr-2"></i>
        糖尿病数据大屏
      </h1>
      <ul class="flex space-x-4">
        <li><a href="{{ url_for('dashboard') }}" class="hover:text-gray-300">数据大屏</a></li>
        <li><a href="{{ url_for('home') }}" class="hover:text-gray-300">首页</a></li>
        <li><a href="{{ url_for('index') }}" class="hover:text-gray-300">预测</a></li>
        <li><a href="{{ url_for('user') }}" class="hover:text-gray-300">用户</a></li>
      </ul>
    </div>
  </nav>

  <!-- 主内容区 -->
  <main class="container mx-auto p-4 md:p-6">
    <!-- 顶部信息栏 -->
    <div class="bg-white rounded-xl p-4 mb-6 card-shadow flex flex-col md:flex-row justify-between items-center">
      <div class="flex items-center mb-4 md:mb-0">
        <div class="bg-primary/10 rounded-full p-3 mr-4 animate-float">
          <i class="fa-solid fa-calendar-days text-primary text-xl"></i>
        </div>
        <div>
          <p class="text-sm text-gray-500">当前日期</p>
          <div class="flex items-center">
            <span id="current-date" class="text-xl font-semibold"></span>
          </div>
        </div>
        <div class="mx-6 h-10 w-px bg-gray-200"></div>
        <div>
          <p class="text-sm text-gray-500">当前时间</p>
          <div class="flex items-center">
            <span id="current-time" class="text-xl font-semibold flex">
              <span class="time-digit">12</span>
              <span class="time-separator mx-1">:</span>
              <span class="time-digit">34</span>
              <span class="time-separator mx-1">:</span>
              <span class="time-digit">56</span>
            </span>
          </div>
        </div>
      </div>
      <div class="flex items-center space-x-3">
        <button id="refresh-btn" class="bg-primary hover:bg-primary/90 text-white px-5 py-2 rounded-lg transition-all duration-300 flex items-center shadow-lg hover:shadow-primary/30">
          <i class="fa-solid fa-refresh mr-2"></i>刷新数据
        </button>
      </div>
    </div>

    <!-- 文件上传区域 -->
    <div class="bg-white rounded-xl p-5 mb-8 card-shadow">
      <div class="flex flex-col md:flex-row justify-between items-center">
        <h2 class="text-lg font-semibold mb-4 md:mb-0">数据上传</h2>
        <div class="flex items-center space-x-4">
          <input type="file" id="csv-file-input" accept=".csv" class="hidden">
          <button id="upload-btn" class="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded-lg transition-all duration-300 flex items-center">
            <i class="fa-solid fa-file-csv mr-2"></i>上传CSV文件
          </button>
          <button id="auto-upload-btn" class="bg-secondary hover:bg-secondary/90 text-white px-4 py-2 rounded-lg transition-all duration-300 flex items-center">
            <i class="fa-solid fa-cloud-upload mr-2"></i>自动上传示例数据
          </button>
        </div>
      </div>
    </div>

    <!-- 数据概览卡片 -->
    <section class="mb-8">
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 md:gap-6">
        <!-- 总样本数 -->
        <div class="bg-white rounded-xl p-5 card-shadow card-hover border border-light">
          <div class="flex justify-between items-start mb-4">
            <div>
              <p class="text-gray-500 text-sm">总样本数</p>
              <h3 class="text-2xl font-bold mt-1 text-primary" id="total-count">--</h3>
            </div>
            <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
              <i class="fa-solid fa-users text-primary"></i>
            </div>
          </div>
          <div class="flex items-center text-xs">
            <div class="w-full bg-gray-200 rounded-full h-1.5">
              <div class="bg-primary h-1.5 rounded-full" id="total-progress" style="width: 0%"></div>
            </div>
            <span class="ml-2 text-gray-500" id="total-percent">0%</span>
          </div>
        </div>

        <!-- 糖尿病患者 -->
        <div class="bg-white rounded-xl p-5 card-shadow card-hover border border-light">
          <div class="flex justify-between items-start mb-4">
            <div>
              <p class="text-gray-500 text-sm">糖尿病患者</p>
              <h3 class="text-2xl font-bold mt-1 text-danger" id="diabetes-count">--</h3>
            </div>
            <div class="w-10 h-10 rounded-full bg-danger/10 flex items-center justify-center">
              <i class="fa-solid fa-user-injured text-danger"></i>
            </div>
          </div>
          <div class="flex items-center text-xs">
            <div class="w-full bg-gray-200 rounded-full h-1.5">
              <div class="bg-danger h-1.5 rounded-full" id="diabetes-progress" style="width: 0%"></div>
            </div>
            <span class="ml-2 text-gray-500" id="diabetes-percent">0%</span>
          </div>
        </div>

        <!-- 非糖尿病患者 -->
        <div class="bg-white rounded-xl p-5 card-shadow card-hover border border-light">
          <div class="flex justify-between items-start mb-4">
            <div>
              <p class="text-gray-500 text-sm">非糖尿病患者</p>
              <h3 class="text-2xl font-bold mt-1 text-secondary" id="non-diabetes-count">--</h3>
            </div>
            <div class="w-10 h-10 rounded-full bg-secondary/10 flex items-center justify-center">
              <i class="fa-solid fa-user-check text-secondary"></i>
            </div>
          </div>
          <div class="flex items-center text-xs">
            <div class="w-full bg-gray-200 rounded-full h-1.5">
              <div class="bg-secondary h-1.5 rounded-full" id="non-diabetes-progress" style="width: 0%"></div>
            </div>
            <span class="ml-2 text-gray-500" id="non-diabetes-percent">0%</span>
          </div>
        </div>

        <!-- 不同性别人数 -->
        <div class="bg-white rounded-xl p-5 card-shadow card-hover border border-light">
          <div class="flex justify-between items-start mb-4">
            <div>
              <p class="text-gray-500 text-sm">糖尿病患者不同性别人数</p>
              <div class="flex items-center mt-2 space-x-6">
                <div class="text-center">
                  <h3 class="text-xl font-bold text-blue-500" id="male-count">--</h3>
                  <p class="text-sm text-gray-500">男</p>
                </div>
                <div class="text-center">
                  <h3 class="text-xl font-bold text-pink-500" id="female-count">--</h3>
                  <p class="text-sm text-gray-500">女</p>
                </div>
              </div>
            </div>
            <div class="w-10 h-10 rounded-full bg-warning/10 flex items-center justify-center">
              <i class="fa-solid fa-venus-mars text-warning"></i>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 图表区域 -->
    <section class="grid grid-cols-1 lg:grid-cols-3 gap-6">
      <!-- 左侧：特征重要性分析和风险因素 -->
      <div class="lg:col-span-1 space-y-6">
        <!-- 特征重要性分析图 -->
        <div class="bg-white rounded-xl p-5 card-shadow border border-light">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold">特征排列重要性分析</h2>
            <div class="flex space-x-2">
              <button class="chart-toggle px-2 py-1 text-xs rounded bg-primary/10 text-primary" data-chart="bar">柱状图</button>
            </div>
          </div>
          <div class="h-[400px]" id="importance-chart"></div>
        </div>

        <!-- 风险因素 -->
        <div class="bg-white rounded-xl p-5 card-shadow border border-light">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold">关键风险因素</h2>
          </div>
          <div id="risk-factors" class="space-y-4">
            <!-- 风险因素将动态填充 -->
          </div>
        </div>
      </div>

      <!-- 中间和右侧：年龄与血糖分布 -->
      <div class="lg:col-span-2 space-y-6">
        <!-- 年龄分布对比 -->
        <div class="bg-white rounded-xl p-5 card-shadow border border-light">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold">年龄分布对比</h2>
            <div class="flex items-center space-x-3">
              <div class="flex items-center">
                <span class="w-3 h-3 rounded-full bg-primary mr-1"></span>
                <span class="text-xs text-gray-500">非糖尿病</span>
              </div>
              <div class="flex items-center">
                <span class="w-3 h-3 rounded-full bg-danger mr-1"></span>
                <span class="text-xs text-gray-500">糖尿病</span>
              </div>
            </div>
          </div>
          <div class="h-[400px]" id="age-chart"></div>
        </div>

        <!-- 血糖与BMI分布 -->
        <div class="bg-white rounded-xl p-5 card-shadow border border-light">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold">血糖与BMI分布</h2>
            <div class="flex space-x-2">
              <button class="filter-btn px-3 py-1 text-xs rounded bg-primary/10 text-primary" data-filter="all">全部</button>
              <button class="filter-btn px-3 py-1 text-xs rounded bg-gray-200 text-gray-600" data-filter="0">非糖尿病</button>
              <button class="filter-btn px-3 py-1 text-xs rounded bg-gray-200 text-gray-600" data-filter="1">糖尿病</button>
            </div>
          </div>
          <div class="h-[320px]" id="glucose-bmi-chart"></div>
        </div>
      </div>
    </section>
  </main>

  <!-- 加载中遮罩 -->
  <div id="loading-overlay" class="fixed inset-0 bg-black/40 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-xl p-6 flex flex-col items-center shadow-2xl">
      <div class="w-12 h-12 border-4 border-gray-200 border-t-primary rounded-full loader mb-4"></div>
      <p id="loading-text" class="text-gray-700">正在处理数据...</p>
    </div>
  </div>


  <script>
    // 全局变量
    let data = null;

    // 显示加载中
    function showLoading(text = '加载中...') {
      document.getElementById('loading-text').textContent = text;
      document.getElementById('loading-overlay').classList.remove('hidden');
    }

    // 隐藏加载中
    function hideLoading() {
      document.getElementById('loading-overlay').classList.add('hidden');
    }

    // 数字动画
    function animateValue(id, start, end, duration) {
      const obj = document.getElementById(id);
      const range = end - start;
      const minTimer = 50;
      let stepTime = Math.abs(Math.floor(duration / range));

      stepTime = Math.max(stepTime, minTimer);

      let startTime = new Date().getTime();
      let endTime = startTime + duration;
      let timer;

      function run() {
        let now = new Date().getTime();
        let remaining = Math.max((endTime - now) / duration, 0);
        let value = Math.round(end - (remaining * range));
        obj.textContent = value;

        if (value == end) {
          clearInterval(timer);
        }
      }

      timer = setInterval(run, stepTime);
      run();
    }

    // 上传CSV文件
    async function uploadCSVFile(file) {
      const formData = new FormData();
      formData.append('csvFile', file);

      try {
        showLoading('正在上传并分析数据...');

        const response = await fetch('/api/upload-csv', {
          method: 'POST',
          body: formData
        });

        if (!response.ok) {
          throw new Error(`HTTP错误，状态码: ${response.status}`);
        }

        const result = await response.json();

        if (result.success) {
          // 处理返回的数据
          processAnalysisResult(result.data);
          return true;
        } else {
          throw new Error(result.error || '处理数据时出错');
        }
      } catch (error) {
        console.error('上传CSV文件失败:', error);
        alert('上传CSV文件失败: ' + error.message);
        return false;
      } finally {
        hideLoading();
      }
    }

    // 处理分析结果
    function processAnalysisResult(apiData) {
      data = apiData;

      // 更新统计信息
      updateStats();

      // 渲染图表
      renderImportanceChart('bar'); // 修改为默认使用柱状图
      renderAgeChart();
      renderGlucoseBmiChart('all');

      // 渲染风险因素
      renderRiskFactors();
    }

    // 更新统计信息
    function updateStats() {
      if (!data) return;

      // 更新DOM
      animateValue('total-count', 0, data.total_samples, 1000);
      animateValue('diabetes-count', 0, data.diabetes_count, 1000);
      animateValue('non-diabetes-count', 0, data.non_diabetes_count, 1000);
      animateValue('male-count', 0, 4039, 1000);
      animateValue('female-count', 0, 4461, 1000);

      // 更新进度条
      document.getElementById('total-progress').style.width = '100%';
      document.getElementById('diabetes-progress').style.width = data.diabetes_percent + '%';
      document.getElementById('non-diabetes-progress').style.width = data.non_diabetes_percent + '%';

      document.getElementById('total-percent').textContent = '100%';
      document.getElementById('diabetes-percent').textContent = data.diabetes_percent.toFixed(1) + '%';
      document.getElementById('non-diabetes-percent').textContent = data.non_diabetes_percent.toFixed(1) + '%';
    }

    // 渲染重要性分析图
    function renderImportanceChart(chartType = 'bar') {
      const featureImportance = [
        { feature: '吸烟史', importance: 0.0014 },
        { feature: '性别', importance: 0.0017 },
        { feature: '心脏病', importance: 0.0034 },
        { feature: '高血压', importance: 0.0097 },
        { feature: 'BMI', importance: 0.0414 },
        { feature: '年龄', importance: 0.0984 },
        { feature: '血糖水平', importance: 0.2764 },
        { feature: 'HbA1c水平', importance: 0.5676 }
      ];

      const chart = echarts.init(document.getElementById('importance-chart'));

      // 根据图表类型设置不同的配置
      let option;
      if (chartType === 'bar') {
        option = {
          backgroundColor: 'transparent',
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            },
            formatter: function(params) {
              return `特征: ${params[0].name}<br>排列重要性: ${params[0].value.toFixed(4)}`;
            }
          },
          xAxis: {
            type: 'category',
            data: featureImportance.map(item => item.feature),
            axisLabel: {
              color: '#718096',
              interval: 0,
              rotate: 45
            },
            axisLine: {
              lineStyle: {
                color: '#E5E9F2'
              }
            },
            axisTick: {
              show: false
            }
          },
          yAxis: {
            type: 'value',
            name: '排列重要性',
            axisLabel: {
              color: '#718096'
            },
            axisLine: {
              lineStyle: {
                color: '#E5E9F2'
              }
            },
            axisTick: {
              show: false
            },
            splitLine: {
              lineStyle: {
                color: '#F5F7FA'
              }
            }
          },
          series: [{
            name: '排列重要性',
            type: 'bar',
            data: featureImportance.map(item => item.importance),
            itemStyle: {
              color: '#165DFF'
            },
            label: {
              show: true,
              position: 'top',
              formatter: function(params) {
                return params.value.toFixed(4);
              },
              textStyle: {
                fontSize: 10
              }
            }
          }]
        };
      }

      chart.setOption(option);

      window.addEventListener('resize', () => {
        chart.resize();
      });
    }

    // 渲染年龄分布图表
    function renderAgeChart() {
      if (!data) return;

      // 年龄区间标签
      const ageLabels = ['0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80'];

      // 分别计算糖尿病患者和非糖尿病患者的年龄分布
      const diabetesData = calculateAgeDistribution(data.raw_data.filter(row => row.diabetes === 1));
      const nonDiabetesData = calculateAgeDistribution(data.raw_data.filter(row => row.diabetes === 0));

      // 初始化图表
      const chart = echarts.init(document.getElementById('age-chart'));

      // 设置图表选项
      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: ['非糖尿病', '糖尿病'],
          textStyle: {
            color: '#1E293B'
          }
        },
        xAxis: {
          type: 'category',
          data: ageLabels,
          axisLabel: {
            color: '#718096'
          },
          axisLine: {
            lineStyle: {
              color: '#E5E9F2'
            }
          },
          axisTick: {
            show: false
          }
        },
        yAxis: {
          type: 'value',
          name: '人数',
          axisLabel: {
            color: '#718096'
          },
          axisLine: {
            lineStyle: {
              color: '#E5E9F2'
            }
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#F5F7FA'
            }
          }
        },
        series: [
          {
            name: '非糖尿病',
            type: 'bar',
            data: nonDiabetesData,
            itemStyle: {
              color: '#165DFF'
            }
          },
          {
            name: '糖尿病',
            type: 'bar',
            data: diabetesData,
            itemStyle: {
              color: '#FF5252'
            }
          }
        ]
      };

      // 应用选项
      chart.setOption(option);

      // 响应窗口大小变化
      window.addEventListener('resize', () => {
        chart.resize();
      });
    }

    // 计算年龄分布的辅助函数
    function calculateAgeDistribution(data) {
      // 创建年龄区间（0-80岁分为8个区间）
      const ageBins = [0, 10, 20, 30, 40, 50, 60, 70, 80];
      const ageLabels = ['0-10', '11-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80'];

      // 使用pd.cut类似的逻辑进行分组统计
      const distribution = ageLabels.reduce((acc, label) => ({ ...acc, [label]: 0 }), {});

      data.forEach(item => {
        const age = parseFloat(item.age);
        for (let i = 0; i < ageBins.length - 1; i++) {
          if (age >= ageBins[i] && age < ageBins[i + 1]) {
            distribution[ageLabels[i]]++;
            break;
          }
        }
      });

      // 将结果转换为数组
      return ageLabels.map(label => distribution[label]);
    }

    // 渲染血糖与BMI分布图表
    function renderGlucoseBmiChart(filter = 'all') {
      if (!data || !data.raw_data) return;

      // 筛选数据
      let filteredData = data.raw_data;
      if (filter !== 'all') {
        filteredData = data.raw_data.filter(row => row.diabetes === parseInt(filter));
      }

      // 提取数据
      const diabetesData = data.raw_data.filter(row => row.diabetes === 1).map(row => [
        parseFloat(row.bmi),
        parseFloat(row.blood_glucose_level),
        parseFloat(row.age)
      ]);

      const nonDiabetesData = data.raw_data.filter(row => row.diabetes === 0).map(row => [
        parseFloat(row.bmi),
        parseFloat(row.blood_glucose_level),
        parseFloat(row.age)
      ]);

      // 初始化图表
      const chart = echarts.init(document.getElementById('glucose-bmi-chart'));

      // 设置图表选项
      const option = {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            return `BMI: ${params.data[0]}<br/>血糖: ${params.data[1]} mg/dL<br/>年龄: ${params.data[2]} 岁`;
          }
        },
        legend: {
          data: ['非糖尿病', '糖尿病'],
          textStyle: {
            color: '#1E293B'
          }
        },
        xAxis: {
          type: 'value',
          name: 'BMI',
          min: 10,
          max: 50,
          axisLabel: {
            color: '#718096'
          },
          axisLine: {
            lineStyle: {
              color: '#E5E9F2'
            }
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#F5F7FA'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '血糖 (mg/dL)',
          min: 50,
          max: 250,
          axisLabel: {
            color: '#718096'
          },
          axisLine: {
            lineStyle: {
              color: '#E5E9F2'
            }
          },
          axisTick: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: '#F5F7FA'
            }
          }
        },
        series: [
          {
            name: '非糖尿病',
            type: 'scatter',
            data: nonDiabetesData,
            symbolSize: 8,
            itemStyle: {
              color: '#36D399',
              opacity: 0.7
            }
          },
          {
            name: '糖尿病',
            type: 'scatter',
            data: diabetesData,
            symbolSize: 8,
            itemStyle: {
              color: '#FF5252',
              opacity: 0.7
            }
          }
        ]
      };

      // 应用选项
      chart.setOption(option);

      // 响应窗口大小变化
      window.addEventListener('resize', () => {
        chart.resize();
      });
    }

    // 渲染风险因素
    function renderRiskFactors() {
      if (!data || !data.risk_factors) return;

      // 清空容器
      document.getElementById('risk-factors').innerHTML = '';

      // 获取风险因素数据
      const riskFactors = data.risk_factors;

      // 渲染每个风险因素
      Object.keys(riskFactors).forEach(key => {
        const factor = riskFactors[key];

        // 创建风险因素卡片
        const card = document.createElement('div');
        card.className = 'bg-light-blue rounded-lg p-3 flex items-center';

        // 根据风险因素ID选择图标
        let iconClass = 'fa-question';
        switch (key) {
          case 'hypertension':
            iconClass = 'fa-heart-pulse';
            break;
          case 'heart_disease':
            iconClass = 'fa-heart-crack';
            break;
          case 'bmi_high':
            iconClass = 'fa-weight-scale';
            break;
          case 'hba1c_high':
            iconClass = 'fa-vial';
            break;
        }

        card.innerHTML = `
          <div class="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center mr-3">
            <i class="fa-solid ${iconClass} text-primary"></i>
          </div>
          <div class="flex-1">
            <h3 class="font-medium">${factor.name}</h3>
            <div class="flex items-center mt-1 text-xs">
              <span class="text-gray-500 mr-2">非糖尿病: ${factor.non_diabetes.toFixed(1)}%</span>
              <span class="text-danger">糖尿病: ${factor.diabetes.toFixed(1)}%</span>
            </div>
          </div>
          <div class="text-right">
            <span class="px-2 py-0.5 rounded-full ${factor.risk_ratio > 1.5 ? 'bg-danger/10 text-danger' : 'bg-warning/10 text-warning'} text-xs">
              ${factor.risk_ratio.toFixed(1)}倍
            </span>
          </div>
        `;

        document.getElementById('risk-factors').appendChild(card);
      });
    }

    // 自动读取预设CSV文件的函数
    async function autoLoadCSVFile() {
      try {
        showLoading('正在加载数据...');

        // 发送请求到服务器端API，指定自动加载的CSV文件
        const response = await fetch('/api/auto-load-csv', {
          method: 'GET'
        });

        if (!response.ok) {
          // 尝试获取服务器返回的JSON格式错误信息
          let errorMessage = `HTTP错误，状态码: ${response.status}`;
          try {
            const errorData = await response.json();
            errorMessage += ` - ${errorData.error || '服务器内部错误'}`;
          } catch (e) {
            // 如果无法解析JSON，使用默认错误信息
          }
          throw new Error(errorMessage);
        }

        const result = await response.json();

        if (result.success) {
          // 处理返回的数据
          processAnalysisResult(result.data);

          // 显示成功消息
          showNotification('数据加载成功', 'success');

          return true;
        } else {
          throw new Error(result.error || '加载数据时出错');
        }
      } catch (error) {
        console.error('自动加载CSV文件失败:', error);

        // 显示错误消息
        showNotification(`自动加载CSV文件失败: ${error.message}`, 'error');

        // 显示手动上传选项作为备用
        document.getElementById('upload-container').style.display = 'block';

        return false;
      } finally {
        hideLoading();
      }
    }

    // 显示通知消息
    function showNotification(message, type = 'info') {
      const notification = document.createElement('div');
      notification.className = `fixed top-4 right-4 px-6 py-3 rounded-lg shadow-lg z-50 transition-all duration-300 transform translate-x-full ${
        type === 'success' ? 'bg-green-500 text-white' :
          type === 'error' ? 'bg-red-500 text-white' : 'bg-blue-500 text-white'
      }`;
      notification.textContent = message;

      document.body.appendChild(notification);

      // 触发动画
      setTimeout(() => {
        notification.classList.remove('translate-x-full');
      }, 10);

      // 3秒后自动关闭
      setTimeout(() => {
        notification.classList.add('translate-x-full');
        setTimeout(() => {
          document.body.removeChild(notification);
        }, 300);
      }, 3000);
    }

    // 页面加载后初始化
    document.addEventListener('DOMContentLoaded', () => {
      // 自动加载数据
      autoLoadCSVFile();

      // 初始化日期时间显示
      updateDateTime();
      setInterval(updateDateTime, 1000);

      // 添加刷新按钮事件监听
      const refreshBtn = document.getElementById('refresh-btn');
      refreshBtn.addEventListener('click', () => {
        // 调用自动加载数据函数
        autoLoadCSVFile();
      });

      // 添加筛选按钮事件监听
      document.querySelectorAll('.filter-btn').forEach(btn => {
        btn.addEventListener('click', () => {
          // 移除所有按钮的活跃状态
          document.querySelectorAll('.filter-btn').forEach(b => {
            b.classList.remove('bg-primary/10', 'text-primary');
            b.classList.add('bg-gray-200', 'text-gray-600');
          });

          // 添加当前按钮的活跃状态
          btn.classList.remove('bg-gray-200', 'text-gray-600');
          btn.classList.add('bg-primary/10', 'text-primary');

          // 渲染图表
          renderGlucoseBmiChart(btn.dataset.filter);
        });
      });

      // 添加图表切换按钮事件监听
      document.querySelectorAll('.chart-toggle').forEach(btn => {
        btn.addEventListener('click', () => {
          // 移除所有按钮的活跃状态
          document.querySelectorAll('.chart-toggle').forEach(b => {
            b.classList.remove('bg-primary/10', 'text-primary');
            b.classList.add('bg-gray-200', 'text-gray-600');
          });

          // 添加当前按钮的活跃状态
          btn.classList.remove('bg-gray-200', 'text-gray-600');
          btn.classList.add('bg-primary/10', 'text-primary');

          // 渲染图表
          renderImportanceChart(btn.dataset.chart);
        });
      });
    });

    // 更新日期时间
    function updateDateTime() {
      const now = new Date();
      const dateOptions = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };

      // 更新日期显示
      document.getElementById('current-date').textContent = now.toLocaleDateString('zh-CN', dateOptions);

      // 更新时间显示（带格式和动画）
      const timeElement = document.getElementById('current-time');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');

      // 使用span包裹每个数字以便应用动画
      timeElement.innerHTML = `
        <span class="time-digit">${hours}</span>
        <span class="time-separator mx-1">:</span>
        <span class="time-digit">${minutes}</span>
        <span class="time-separator mx-1">:</span>
        <span class="time-digit">${seconds}</span>
      `;
    }
  </script>
</body>
</html>